<template>
  <div class="container">
    <van-nav-bar
      fixed
      title="注册账号"
      @click-left="$router.back()"
      left-arrow
    />

    <div class="logo-txt">欢迎注册</div>
    <van-form @submit="onSubmit" label-width="70px">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        left-icon="manager"
        :rules="[{ required: true, message: '请填写手机号' },
         { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确的手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        left-icon="lock"
        :rules="[{ required: true, message: '请填写密码' },
         { pattern: /^\d{6,12}$/, message: '请输入6-12位数字组成的密码' }]"
      />
      <van-field
        v-model="password1"
        type="password"
        name="password1"
        label="确认密码"
        placeholder="确认密码"
        left-icon="lock"
        :rules="[{ required: true, message: '请填写密码' },
        { pattern: /^\d{6,12}$/, message: '请输入6-12位数字组成的密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >立即注册</van-button
        >
      </div>
    </van-form>
    <van-row type="flex" justify="end">
      <van-col :span="10">
        <router-link to="/login">已有账号,请登录</router-link>
      </van-col>
    </van-row>
  </div>
</template>

<script>
import { register } from '@/api/user'
import { Toast } from 'vant'
export default {
  name: 'regPage',
  data () {
    return {
      mobile: '',
      password: '',
      password1: ''
    }
  },
  methods: {
    async  onSubmit (values) {
      console.log(values)
      if (values.password !== values.password1) {
        Toast.fail('两次密码不一致')
        this.password1 = ''
      } else {
        const res = await register(values)
        if (res.errno === 0) {
          Toast.success('注册成功')
          this.$router.push('/login')
        } else if (res.errno === 1000) {
          Toast.fail('手机号已存在！')
          this.mobile = ''
          this.password = ''
          this.password1 = ''
        }
      }
    }
  }
}
</script>

<style scoped>
.logo-txt {
  text-align: center;
  font-size: 60px;
  margin: 60px auto;
  color: #1989fa;
}
</style>
